import {
  added,
  selectSellPage,
  getCategoryEffect,
} from '@/services/goods/productManageApproval';
import { ProTable } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';

import { useDispatch, useSelector } from '@umijs/max';
import { App, DatePicker, Form, Modal, Radio, Space } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef } from 'react';
import { columns } from './columns';

const currentPermissions = JSON.parse(localStorage.getItem('currentPermissions'));

export default function Tables() {
  const ref = useRef();
  const [form] = Form.useForm();
  const { productManageApproval, groupManage, loading, supplier } = useSelector((state) => state);
  const { activeKey, select, modalData, type, isModalOpen, itemSkuVos, srks, showForm } =
  productManageApproval;
  const { suppliersList } = supplier;
  const { categoryTree, categoryList } = groupManage;
  const { message } = App.useApp();
  const dispatch = useDispatch();

  useEffect(() => {
    if (activeKey) {
      ref?.current?.reload();
    }
  }, [activeKey]);

  const onSuccess = ({ code }) => {
    if (code && code === 200) {
      dispatch({
        type: 'productManageApproval/update',
        payload: {
          isModalOpen: false,
          modalData: { groundType: 1 },
          srks: [],
        },
      });
      ref?.current?.reload();
    }
  };

  // 同意
  const { run: deleteAsync } = useRequest(
    getCategoryEffect,
    {
      manual: true,
      onSuccess: onSuccess
    }
  );

  const handleEdit = (type, record) => {
    dispatch({
      type: 'productManageApproval/update',
      payload: {
        type: type,
      },
    });
    //同意
    if (type === 'agree') {
      deleteAsync({
        id:record.id,
        auditStatus:99,
      });
    }
    // 驳回
    if (type === 'unAgree') {
      dispatch({
        type: 'productManageApproval/update',
        payload: {
          showForm: true,
          queryInfo: record,
        },
      });
    }
  };

  const handler = (data) => {
    return data.map((item) => {
      const obj = { label: item?.label || '', value: item?.id };
      if (item?.children && item?.children.length > 0) {
        obj.children = handler(item.children);
      }
      return obj;
    });
  };
  const options = () => {
    if (categoryTree.length > 0) {
      const newArr = [];
      handler(categoryTree).forEach((item) => {
        if (item?.value !== '0') {
          newArr.push(item);
        }
      });
      return newArr;
    } else {
      return [];
    }
  };
  // 供应商枚举
  const suppliersEnum = () => {
    const obj = {};
    suppliersList.forEach((item) => {
      obj[item?.supplierId] = { text: item?.supplierName };
    });
    return obj;
  };
  return (
    <>
      <ProTable
        className="the-pro-table"
        actionRef={ref}
        options={false}
        search={{
          labelWidth: 70,
          labelAlign: 'right',
          style: {
            padding: '24px 0px',
          },
        }}
        params={{
          showForm: showForm,
        }}
        request={async (params = {}) => {
          const {
            current,
            pageSize,
            price,
            createTimeRange,
            sellTimeRange,
            suppliersId,
            ...formData
          } = params;
          let status = {};
          // 出售中=== 已上架&&开售时间>=当前时间
          if (activeKey === '1') {
            status = { onShelf: 2, groundType: 2 };
          }
          // 仓库中=== 待上架&&开售时间===null
          if (activeKey === '2') {
            status = { onShelf: 0 };
          }
          // 待开售=== 已上架&&开售时间<当前时间
          if (activeKey === '3') {
            status = { onShelf: 2, groundType: 1 };
          }
          // 全部
          if (activeKey === '4') {
            status = {};
          }
          let body = {
            pageNum: current,
            pageSize,
            ...status,
            ...formData,
            suppliersId: suppliersId && Number(suppliersId),
            minPrice: price?.[0],
            maxPrice: price?.[1],
            startTime: createTimeRange?.[0] ? `${createTimeRange[0]} 00:00:00` : undefined,
            endTime: createTimeRange?.[1] ? `${createTimeRange[1]} 23:59:59` : undefined,
            minOpenTime: sellTimeRange?.[0] ? `${sellTimeRange[0]} 00:00:00` : undefined,
            maxOpenTime: sellTimeRange?.[1] ? `${sellTimeRange[1]} 23:59:59` : undefined,
          };
          if (formData?.categoryId && formData?.categoryId.length > 0) {
            body.categoryId = formData?.categoryId[formData?.categoryId.length - 1];
          }
          const { code, data, total } = await selectSellPage(body);
          if (code && code === 200) {
            dispatch({
              type: 'productManage/update',
              payload: {
                select: { selectedRowKeys: [], selectedRows: [] },
                reload: false,
              },
            });
            return {
              data: data || [],
              total: total,
              success: true,
            };
          }
        }}
        pagination={{
          showSizeChanger: true,
        }}
        cardProps={{
          size: 'small',
          style: {
            padding: 0,
          },
        }}
        cardBordered={false}
        columns={columns({ handleEdit, options, categoryList, suppliersEnum, currentPermissions })}
        rowKey="id"
        rowSelection={{
          selectedRowKeys: select.selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            dispatch({
              type: 'productManageApproval/update',
              payload: {
                select: { selectedRowKeys: selectedRowKeys, selectedRows: selectedRows },
              },
            });
          },
        }}
        scroll={{ x: 1300 }}
      />
      <Modal
        destroyOnClose
        open={isModalOpen}
        onCancel={() => {
          onSuccess({ code: 200 });
        }}
        title={
          <span style={{ color: 'RGB(26,158,215)' }}>
            {type === 'upload' &&
              (srks.length > 1 ? `确定批量上架选中的${srks.length}个商品吗?` : `确定上架该商品吗?`)}

            {type === 'down' &&
              (srks.length > 1 ? `确定批量下架选中的${srks.length}个商品吗?` : `确定下架商品吗?`)}

            {type === 'delete' &&
              (srks.length > 1 ? `确定批量删除选中的${srks.length}个商品吗?` : `确定删除商品?`)}
          </span>
        }
        okText={
          <span>
            {type === 'upload' && '上架'}
            {type === 'down' && '下架'}
            {type === 'delete' && '删除'}
          </span>
        }
        onOk={() => {
          if (type === 'upload') {
            uploadAsync(
              srks.map((item) => ({
                id: item && Number(item),
                ...form.getFieldsValue(),
                openTime: form.getFieldsValue()?.openTime
                  ? dayjs(form.getFieldsValue()?.openTime).format('YYYY-MM-DD HH:mm:ss')
                  : null,
              })),
            );
          }

          if (type === 'down') {
            downAsync({ ids: srks.map((item) => Number(item)) });
          }
          if (type === 'delete') {
            deleteAsync(srks.map((item) => Number(item)));
          }
        }}
      >
        <>
          {type === 'upload' && (
            <div>
              <Form
                form={form}
                labelAlign="left"
                preserve={false}
                labelCol={{
                  span: 8,
                }}
                wrapperCol={{
                  span: 16,
                }}
                colon={false}
                layout="horizontal"
                style={{}}
                initialValues={{
                  groundType: 1,
                  openTime: dayjs(),
                }}
                onValuesChange={(val, vals) => {
                  dispatch({
                    type: 'productManageApproval/update',
                    payload: { modalData: vals },
                  });
                }}
              >
                <Form.Item label="上架时间" name="groundType">
                  <Radio.Group>
                    <Space direction="vertical">
                      <Radio value={1}>立即上架</Radio>
                      <Radio value={2}>定时上架</Radio>
                    </Space>
                  </Radio.Group>
                </Form.Item>
                <Form.Item label=" " name="openTime">
                  <DatePicker
                    disabled={modalData?.groundType === 1}
                    placeholder="请选择上架时间"
                    showTime={{
                      format: 'HH:mm',
                    }}
                    format="YYYY-MM-DD HH:mm"
                  />
                </Form.Item>
              </Form>
            </div>
          )}
          {type === 'down' && <p>下架商品将迁移入[仓库中]中</p>}
          {type === 'delete' && <p>商品删除后不可见，请谨慎操作</p>}
        </>
      </Modal>
    </>
  );
}
